/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

// 等待设备就绪
document.addEventListener('deviceready', function() {
    console.log('设备就绪，藏头诗功能可用');
}, false);

// 表单提交处理
document.getElementById('poem-form').addEventListener('submit', function(e) {
    e.preventDefault();
    generatePoem();
});

// 生成藏头诗
function generatePoem() {
    const form = document.getElementById('poem-form');
    const submitBtn = document.getElementById('submit-btn');
    const loading = document.getElementById('loading');
    const errorMessage = document.getElementById('error-message');
    const resultContainer = document.getElementById('result-container');
    
    // 获取表单数据
    const formData = {
        token: document.getElementById('token').value.trim(),
        keyword: document.getElementById('keyword').value.trim(),
        num: document.getElementById('num').value,
        type: document.getElementById('type').value,
        rhyme: document.getElementById('rhyme').value
    };
    
    // 验证关键字长度
    if (formData.keyword.length < 2 || formData.keyword.length > 8) {
        showError('关键字长度必须在2-8个字之间');
        return;
    }
    
    // 验证token
    if (!formData.token) {
        showError('请输入API Token');
        return;
    }
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitBtn.textContent = '生成中...';
    loading.classList.add('show');
    errorMessage.classList.remove('show');
    resultContainer.classList.remove('show');
    
    // 构建请求参数
    const params = new URLSearchParams();
    params.append('token', formData.token);
    params.append('keyword', formData.keyword);
    params.append('num', formData.num);
    params.append('type', formData.type);
    params.append('rhyme', formData.rhyme);
    
    // 发送POST请求
    fetch('https://v3.alapi.cn/api/ai/poem', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: params.toString()
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络请求失败: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('API响应:', data);
        
        if (data.success && data.code === 200) {
            displayPoem(data.data);
        } else {
            showError(data.message || '生成失败，请检查参数');
        }
    })
    .catch(error => {
        console.error('请求错误:', error);
        showError('请求失败: ' + error.message + '。请检查网络连接或API Token是否正确');
    })
    .finally(() => {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.textContent = '生成藏头诗';
        loading.classList.remove('show');
    });
}

// 显示错误信息
function showError(message) {
    const errorMessage = document.getElementById('error-message');
    errorMessage.textContent = message;
    errorMessage.classList.add('show');
}

// 显示生成的诗词
function displayPoem(data) {
    const resultContainer = document.getElementById('result-container');
    const poemText = document.getElementById('poem-text');
    const poemList = document.getElementById('poem-list');
    
    // 显示诗词文本
    if (data.poem) {
        poemText.textContent = data.poem;
    } else {
        poemText.textContent = '未生成诗词内容';
    }
    
    // 显示诗词列表
    poemList.innerHTML = '';
    if (data.list && Array.isArray(data.list)) {
        data.list.forEach((line, index) => {
            const li = document.createElement('li');
            li.textContent = `${index + 1}. ${line}`;
            poemList.appendChild(li);
        });
    }
    
    // 显示结果容器
    resultContainer.classList.add('show');
    
    // 滚动到结果区域
    resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 尝试从本地存储加载token
    const savedToken = localStorage.getItem('poem_api_token');
    if (savedToken) {
        document.getElementById('token').value = savedToken;
    }
    
    // 保存token到本地存储
    document.getElementById('token').addEventListener('blur', function() {
        const token = this.value.trim();
        if (token) {
            localStorage.setItem('poem_api_token', token);
        }
    });
    
    console.log('藏头诗页面加载完成');
});

